﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml;
using Wicresoft.EVM.Reporting.Model;

namespace Wicresoft.EVM.Reporting
{
    public static class Util
    {
        public static readonly string ReportServerUrl = ConfigurationManager.AppSettings["ReportServer"];
        public static readonly string DoAuthenticate = ConfigurationManager.AppSettings["DoAuthenticate"];
        public static readonly string ARReportingUrl = ConfigurationManager.AppSettings["ARReportingUrl"];
        public static readonly string ARSSOUrl = ConfigurationManager.AppSettings["ARSSOUrl"];
        public static readonly string ARSSODomain = ConfigurationManager.AppSettings["ARSSODomain"];
        public static readonly string WebsiteUrl = ConfigurationManager.AppSettings["WebsiteUrl"];
        public static readonly string ErrorUrl = ConfigurationManager.AppSettings["ErrorUrl"];
        public static readonly string AccessDeniedUrl = ConfigurationManager.AppSettings["AccessDeniedUrl"];
        public static readonly string ARHomepageUrl = ConfigurationManager.AppSettings["ARHomepageUrl"];
        //using following account to access reporting service.
        public static readonly string ReportingUserName = ConfigurationManager.AppSettings["ReportingUserName"];
        public static readonly string ReportingUserPSW = ConfigurationManager.AppSettings["ReportingUserPSW"];
        public static readonly string ReportingUserDomain = ConfigurationManager.AppSettings["ReportingUserDomain"];
      

        public static ARUser LogonUser
        {
            get
            {
                // if auth is turned off, we create a test user with several permissions
                if (!Auth)
                    return new ARUser
                    {
                        Name = "Demo User",
                        Role = ReportViewer.VM_Report_Viewer | ReportViewer.Request_Report_Viewer | ReportViewer.Cost_Report_Viewer | ReportViewer.Resource_Pool_Report_Viewer,
                    };


                var user = HttpContext.Current.Session["ARUser"] as ARUser;
                if (user == null)
                {
                    HttpContext.Current.Response.Redirect(ARReportingUrl);
                }
                return user;
            }
            private set
            {
                HttpContext.Current.Session["ARUser"] = value;
            }
        }

        public static bool Auth
        {
            get
            {
                return bool.Parse(DoAuthenticate);
            }
        }

        public static IEnumerable BuildMenu()
        {
            ReportViewer current = 0;

            var r = HttpContext.Current.Request.QueryString["r"];
            if (r != null)
                current = (ReportViewer)int.Parse(r);
            else
                current = Reports.Keys.FirstOrDefault(p => (p & LogonUser.Role) != 0);

            foreach (var report in Reports)
            {
                if ((report.Key & LogonUser.Role) != 0)
                    yield return new
                    {
                        CssClass = report.Key == current ? "current" : "",
                        Text = report.Value[0],
                        ReportType = (int)report.Key,
                    };
            }
        }


        private static IDictionary<ReportViewer, string[]> rpt;
        public static IDictionary<ReportViewer, string[]> Reports
        {
            get
            {
                if (rpt == null)
                {
                    rpt = new Dictionary<ReportViewer, string[]>();

                    rpt.Add(ReportViewer.VM_Report_Viewer, new string[] { "VM Status Report", "/vm-status" });
                    rpt.Add(ReportViewer.Resource_Pool_Report_Viewer, new string[] { "Resource Pool Report", "/resource-pool" });
                    rpt.Add(ReportViewer.Business_Service_Report_Viewer, new string[] { "Business Service Report", "/business-service" });
                    rpt.Add(ReportViewer.Request_Report_Viewer, new string[] { "Service Request Report", "/service-request" });
                    rpt.Add(ReportViewer.Cost_Report_Viewer, new string[] { "Cost Report", "/cost" });
                }
                return rpt;
            }
        }

        public static bool TryAuthenticate(string sid)
        {
            string body;

            CookieContainer cookies = new CookieContainer();
            cookies.Add(new Cookie("JSESSIONID", sid, "/", ARSSODomain));

            NameValueCollection headers = new NameValueCollection();
            headers.Add("sso-jsp-asp", Guid.NewGuid().ToString());

            try
            {
                HttpStatusCode code = WebUtil.Request(ARSSOUrl, out body, "POST", cookies, headers);
                if (code == HttpStatusCode.OK)
                {
                    string user = body.Trim();
                    ReportViewer role = GetRole(user);

                    LogonUser = new ARUser() { Name = user, Role = role };
                    return true;
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        private static ReportViewer GetRole(string user)
        {
            if (string.IsNullOrEmpty(user))
                throw new ArgumentNullException("user");

            ReportViewer role = new ReportViewer();

            using (ARSysContext dc = new ARSysContext())
            {
                var sql = from groups in dc.Groups
                          from people in dc.People
                          from pg in dc.PGAssociations
                          where people.PeopleId == pg.PeopleId
                          where groups.GroupId == pg.GroupId
                          where people.CIL == user
                          select groups.Name;

                foreach (var r in sql)
                {
                    if (ReportViewerUtil.AllRoles.Keys.Contains(r))
                        role |= ReportViewerUtil.AllRoles[r];
                }
            }

            return role;
        }


    }
}